package com.vybfi.pma.controllers;


import com.vybfi.pma.dao.ProjectRepository;
import com.vybfi.pma.dao.StudentRepository;
import com.vybfi.pma.entities.Project;
import com.vybfi.pma.entities.Student;
import com.vybfi.pma.services.ProjectService;
import com.vybfi.pma.services.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Iterator;
import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("projects")
public class ProjectController {

    @Autowired
    ProjectService projectService;

    @Autowired
    StudentService studentService;

    @GetMapping()
    public String displayStudent(Model model){
        List<Project> projects=projectService.getAll();
        model.addAttribute("projects",projects);
        return "projects/list-projects";
    }

    @GetMapping("/new")
    public String displayProjectForm(Model model){
        Project aProject = new Project();
        List<Student> students = studentService.getAll();
        model.addAttribute("project",aProject);
        model.addAttribute("allStudents",students);
        return "projects/new-project";
        //返回 "new-project" 为templates中的HTML模板的名字，无需添加后缀名。
    }

    @PostMapping("/save")
    public String createProject(Model model, @RequestParam List<Long> students, Project project){
        //将用户写入的表单存入数据库
        projectService.save(project);
        //防止重复提交-退回原网页？
        return "redirect:/projects/new";
    }



}
